package org.alexsotob.roo.addon.flyway;

import org.springframework.roo.support.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DataNucleusPersistenceFileModifier implements
		PersistenceFileModifier {

	private static final String AUTO_CREATE_SCHEMA_PROPERTY = "datanucleus.autoCreateSchema";
	private static final String AUTO_CREATE_TABLES = "datanucleus.autoCreateTables";
	private static final String AUTO_CREATE_COLUMNS = "datanucleus.autoCreateColumns";
	private static final String AUTO_CREATE_CONSTRAINTS = "datanucleus.autoCreateConstraints";

	@Override
	public void avoidDatabaseAutoCreation(Document persistenceDocument) {

		setAttributeToFalse(persistenceDocument, AUTO_CREATE_SCHEMA_PROPERTY);
		setAttributeToFalse(persistenceDocument, AUTO_CREATE_TABLES);
		setAttributeToFalse(persistenceDocument, AUTO_CREATE_COLUMNS);
		setAttributeToFalse(persistenceDocument, AUTO_CREATE_CONSTRAINTS);

	}

	private void setAttributeToFalse(Document persistenceDocument,
			String propertyName) {
		Element synchronizeMappingsProperty = XmlUtils.findFirstElement(
				"/persistence/persistence-unit/properties/property[@name= '"
						+ propertyName + "']",
				persistenceDocument.getDocumentElement());

		if (synchronizeMappingsProperty != null) {
			synchronizeMappingsProperty.setAttribute("value", "false");
		}
	}

}
